<template>
	<view>
		<!-- pages/goodsDetail/order/index.wxml -->
		<!-- 头部 -->
		<navber id="head-navber" :navbarData="navbarData"></navber>

		<!-- 地址 -->
		<view class="address" v-if="errorMsg == ''">
			<view class="address-img">
				<image
					:src="imgUrl + '/imgs/submitOrder/' + (userAddress.take_phone ? 'have_data' : 'not_data') + '.png'">
				</image>
			</view>
			<view class="address-info">
				<view class="address-info-np" v-if="userAddress.take_phone">
					<view class="address-info-np-name">{{ userAddress.take_name }}</view>
					<view class="address-info-np-phone">{{ userAddress.take_phone }}</view>
				</view>
				<view class="address-info-detail" v-if="userAddress.take_phone">
					{{ userAddress.province }} {{ userAddress.city }} {{ userAddress.district }}
					{{ userAddress.detail_address }}
				</view>
				<view class="address-info-switch" @tap="onUserAddress">{{ userAddress.take_phone ? '切换地址' : '请添加收货地址' }}></view>
			</view>
		</view>
		<!-- 商品订单 -->

		<view class="order" v-if="errorMsg == ''" v-for="(item, index) in orderData.list" :key="index">
			<view class="order-item">
				<view class="cart-store-line">
					<view class="cart-store-img" @tap="onItemSelectStore($event, { index })" :data-index="index">
						<image :src="item.store['store_label']"></image>
					</view>
					<view class="cart-store-name">{{ item.store['store_name'] }}</view>
				</view>
				<view class="cart-goods-item" v-for="(itemx, indexx) in item.list" :key="itemx.indexx">
					<view class="order-item-img">
						<image mode="aspectFill" :src="itemx.goods_img"></image>
					</view>

					<view class="order-item-info">
						<view class="order-item-info-title">{{ itemx.goods_title }}</view>
						<view class="order-item-info-text-title-attr">
							<view >{{ itemx.attribute_names }}</view>
						</view>
						<!-- <span class="price-discounts-bean" v-if="bean=='bean'">{{parseInt(itemx.goods_price)}}
							趣豆</span> -->
						<view class="order-item-info-pn">
							<view class="order-item-info-pn-price">
								<span class="tip">¥</span>
								{{ itemx.goods_price }}
							</view>
							<view class="order-item-info-pn-number">
								<!-- <view>
									<span class="tip">X</span>
									{{ itemx.goods_number }}
								</view> -->
									<van-stepper
									    input-class="goods-number-input"
									    :value="itemx.goods_number"
									    min="1"
									    :max="itemx.goods_storage"
									    @change="onNumChange($event, { index, indexx })"
									    :data-index="index"
									    :data-indexx="indexx"
									/>
								<!-- <numinput :index="index + ''" :indexx="indexx + ''"
									:num="itemx.goods_number" :maxNum="itemx.goods_storage" @change="numChange">
								</numinput> -->
								<!-- <view v-if="showType == 'pt_order'" class="order-item-info-pn-pt">拼团</view> -->
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="order-item-bottom">
			<view class="order-info-all">
				<view class="fund" v-if="bean=='bean'||bean=='gift'">
					<view v-if="bean=='bean'">
						兑换券：
						<span class="fund-price">¥{{couponPrice}}</span>
						<span class="fund-modify" @tap.native="openFund">选择</span>
					</view>
					<view v-if="bean=='gift'">
						优惠：
						<span class="fund-price">¥{{discountsPrice}}</span>
					</view>
				</view>
				<view class="fund" v-else></view>

				<view class="freight">
					运费：
					<span>¥{{ orderData.freight }}</span>
				</view>
			</view>

			<view class="line-info-top" v-if="beanSum>0&&bean=='bean'"></view>
			<view class="order-info-all" v-if="beanSum>0&&bean=='bean'">
				<view class="fund" v-if="bean=='bean'">
					<view>
						当前趣豆：
						<span class="fund-price">{{beanSum}}</span>
					</view>
				</view>
				<view class="fund" v-else></view>
				<view class="freight">

				</view>
			</view>
			<view class="line-info"></view>
			<view class="order-msg">
				<view class="order-msg-title">
					<view class="order-msg-title-tip">买家留言：</view>
				</view>
				<view class="order-msg-input">
					<view class="order-msg-input-text">
						<textarea placeholder="选填，请填写您的备注信息" @input="inputBuyMsg"></textarea>
					</view>
				</view>
			</view>
		</view>
		<view class="not-data" v-if="errorMsg != ''">
			<image :src="imgUrl + '/imgs/not_res_bg.png'"></image>
			<view class="error-msg-text">{{ errorMsg }}</view>
		</view>
		<view class="end"></view>
		<!-- 提交 -->
		<view class="submit" v-if="errorMsg == ''">
			<view class="submit-price">
				<view class="submit-price-title">实际支付：</view>
				<view class="submit-price-number">¥{{ orderData.count_goods_price-discountsPrice }}</view>
			</view>
			<view class="submit-but" @tap="createOrder">提交订单</view>
		</view>
		<van-popup :show="couponShow" closeable :round="true" @close="onCloseCoupon" @click-overlay="onCloseCoupon">
			<view class="coupon-list">
				<coupon v-for="(item,index) in couponList" :key="index" :couponData="item" @selectCou="getSelectCou">
				</coupon>
			</view>
		</van-popup>
		<van-popup :show="discountsShow" closeable :round="true" @close="onCloseDiscounts"
			@click-overlay="onCloseDiscounts">
			<view class="discounts" @click="onSeDiscounts">
				<image src="http://yinjia.oss-cn-beijing.aliyuncs.com/haizili/discounts.png"></image>
				<view class="discounts-price"><span>¥</span>{{discountsPrice}}</view>
			</view>
		</van-popup>
	</view>
</template>

<script>
	import navber from '@/components/navber/index';
	import numinput from '@/components/numinput/index';
	import coupon from '@/components/coupon/coupon';
	// pages/goodsDetail/order/index.js
	const Config = require('../../../config/index.js');

	const Api = require('../../../api/index.js');

	const Util = require('../../../utils/sys-util.js');

	const app = getApp();
	export default {
		components: {
			navber,
			numinput,
			coupon
		},
		data() {
			return {
				navbarData: {
					title: '提交订单' //顶部标题
				},
				//导航栏
				imgUrl: Config.imgUrl,
				//图片url
				userAddress: {
					city: '',
					detail_address: '',
					district: '',
					id: 0,
					province: '',
					take_name: '',
					take_phone: ''
				},
				show: false,
				errorMsg: '',
				showType: '',
				goods_id: '',
				//商品id
				bean: '',
				//团购分组id
				goods_number: '',
				//商品对应id 商品数量
				goods_number_arr: [],
				goods_info: '',
				orderData: [],
				//数据
				buy_msg: '',
				beanSum: 0,
				beanChecked: 1,
				couponShow: false,
				couponList: [{
					price: 50,
					detail: "商品兑换券",
					id: 1
				}],
				couponPrice: 0,
				discountsShow: false,
				discountsPrice: 0, //随机优惠
				couponId: 0,
				//留言
				public_type: 0 //是否参与公益 2愿意，4不愿意
			};
		},
		onLoad(e) {
			// console.log(e);
			this.setData({
				showType: e.type,
				goods_info: e.goods_info,
				goods_id: e.goods_id ? e.goods_id : 0,
				bean: e.bean ? e.bean : "",
			});
			this.getData();
		},

		onShow() {
			this.getData();
		},
		onPullDownRefresh: function() {
			this.getData();
			uni.stopPullDownRefresh();
		},
		methods: {
			getData() {
				//获取数据
				var json = {
					showType: this.showType,
					goods_id: this.goods_id,
					goods_group: this.group_id,
					goods_info: this.goods_info
				};
				Api.orderShow(json).then((res) => {
					if (res.code == 1) {
						this.setData({
							orderData: res.data,
							beanSum: res.data.bean,
							userAddress: res.data.userAddress ? res.data.userAddress : {},
							couponList: res.data.couponList,
						});
						if (this.bean == 'gift') {
							this.discountsShow = true;
							this.discountsPrice = this.getDiscounts();
						}
						// console.log(res.data);
						// let datax = res.data.list;
						// let goods_number_arr_temp = [];
						// for (var key in datax) {
						//   for(var keyx in datax[key].list){
						//     goods_number_arr_temp[key+'_'+keyx] = datax[key].list[keyx]['goods_number'];
						//   }
						// }
						// this.setData({
						//   goods_number_arr: goods_number_arr_temp
						// });
					} else {
						this.setData({
							errorMsg: res.msg
						});
					}
				});
			},
			onCloseDiscounts() {
				this.discountsShow = false;
				this.discountsPrice = 0;
			},
			onSeDiscounts() {
				this.discountsShow = false;
			},
			onCloseCoupon() {
				this.couponId = 0;
				this.couponPrice = 0;
				this.couponShow = false;
			},
			onChangeBean(e) {
				this.beanChecked = this.beanChecked == 0 ? 1 : 0;
			},
			getSelectCou(e) {
				// console.log(e);
				this.couponId = e.detail.id;
				this.couponPrice = e.detail.price;
				this.couponShow = false;
			},
			onUserAddress(e, _dataset) {

				if (!e.currentTarget) {
					if (_dataSet.tagId) {
						e.currentTarget = {
							id: _dataSet.tagId
						};
					} else {
						e.currentTarget = {
							dataset: _dataSet
						};
					}
				}

				//用户地址
				var _this = this;

				uni.navigateTo({
					url: '/pages/user/address/index',
					events: {
						// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
						addressInfo: function(res) {
							_this.setData({
								userAddress: res.data
							});
						}
					},
					success: function(res) {
						// // 通过eventChannel向被打开页面传送数据
						res.eventChannel.emit('set_order_select', {
							data: '传入数据'
						});
					}
				});
			},

			inputBuyMsg(e, _dataset) {

				if (!e.currentTarget) {
					if (_dataSet.tagId) {
						e.currentTarget = {
							id: _dataSet.tagId
						};
					} else {
						e.currentTarget = {
							dataset: _dataSet
						};
					}
				}

				//用户备注信息
				this.setData({
					buy_msg: e.detail.value
				});
			},

			createOrder(e, _dataset) {

				if (!e.currentTarget) {
					if (_dataSet.tagId) {
						e.currentTarget = {
							id: _dataSet.tagId
						};
					} else {
						e.currentTarget = {
							dataset: _dataSet
						};
					}
				}

				//创建订单
				var address = this.userAddress;

				if (!address.id) {
					uni.showToast({
						title: '请选择地址',
						icon: 'none'
					});
					return;
				} // var goods_id = "";
				// var data = this.data.orderData.list;
				// for (var i = 0; i < data.length;i++){
				//   //商品订单
				//   goods_id += goods_id == "" ? data[i].id : "," + data[i].id;
				// }
				// var goods_number = this.data.goods_number;
				// console.log(goods_number);
				// if (goods_number.indexOf(",") > 0) {
				//   goods_number = this.data.goods_number_arr.join(",");
				// } else {
				//   goods_number = this.data.goods_number_arr[0];
				// }

				var json = {
					showType: this.showType,
					goods_id: this.goods_id,
					goods_group: this.group_id,
					goods_info: this.goods_info,
					buy_msg: this.buy_msg,
					address_id: this.userAddress.id,
					top_code: app.globalData.top_code,
					bean: this.bean,
					discounts: this.discountsPrice,
					couponId: this.couponId
				};
				Api.orderCreate(json).then((res) => {
					if (res.code == 1) {
						uni.redirectTo({
							url: '/pages/pay/show/index?order_id=' + res.data.order_id + '&pay_type=pay' +
								'&bean=' + this.bean
						});
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				});
			},
			onNumChange(e, _dataset) {
				if (!e.currentTarget) {
					if (_dataSet.tagId) {
						e.currentTarget = {
							id: _dataSet.tagId
						};
					} else {
						e.currentTarget = {
							dataset: _dataSet
						};
					}
				}
				let goods_number = e.detail;
				var index = parseInt(e.currentTarget.dataset.index);
				var indexx = parseInt(e.currentTarget.dataset.indexx);
				var data = this.orderData.list;
				var goods_id =  data[index].list[indexx].goods_id;
				var attribute_ids = data[index].list[indexx].attribute_ids;
				var index = this.getGoodsInfoIndex(goods_id,attribute_ids);
				var goods_info_temp = JSON.parse(this.goods_info);
				goods_info_temp[index].goods_number = goods_number;
				this.setData({
					goods_info: JSON.stringify(goods_info_temp)
				});
				this.getData();
				// console.log(this.goods_info);
			},
			openFund() {
				// console.log(this.beanChecked);
				this.setData({
					couponShow: true
				});
			},

			onItemSelectStore(e, _dataset) {

				if (!e.currentTarget) {
					if (_dataSet.tagId) {
						e.currentTarget = {
							id: _dataSet.tagId
						};
					} else {
						e.currentTarget = {
							dataset: _dataSet
						};
					}
				}
			},
			getGoodsInfoIndex(goods_id, attribute_ids) {
				let goods_info = JSON.parse(this.goods_info);
				let index = -1;
				goods_info.forEach((element, indexx) => {
					if((element.goods_id+'')==(goods_id+'')&&(element.attribute_ids+'')==(attribute_ids+'')){
						index = indexx;
					}
				});
				return index;
			},
			getDiscounts() {
				var discountsPrice = 0;
				switch (parseInt(this.orderData.count_goods_price)) {
					case 500:
						discountsPrice = ((10 + (Math.random() * 5)) / 10).toFixed(2);
						break;
					case 1000:
						discountsPrice = ((10 + (Math.random() * 10)) / 10).toFixed(2);
						break;
					case 2000:
						discountsPrice = ((15 + (Math.random() * 25)) / 10).toFixed(2);
						break;
					case 3000:
						discountsPrice = ((20 + (Math.random() * 40)) / 10).toFixed(2);
						break;
					case 4000:
						discountsPrice = ((30 + (Math.random() * 20)) / 10).toFixed(2);
						break;
				}
				return discountsPrice;
			}
		}
	};
</script>
<style>
	@import './index.css';
</style>
